import { createSlice } from '@reduxjs/toolkit'
import { getSongCategory, getSongCategoryList } from '../service/songs'
import { createAsyncThunk } from '@reduxjs/toolkit'
import type { songsStateType, currentCategoryType } from './type'


export const fetchCategoryAction = createAsyncThunk(
  'category',
  async (arg, { dispatch }) => {
    getSongCategory().then((res) => {
      console.log(res)
      dispatch(CategoryAction(res))
    })
  }
)

export const fetchChangeCategoryAction = createAsyncThunk(
  'categoryList',
  async (
    catOrParams: string | { cat: string; offset?: number; limit?: number },
    { dispatch }
  ) => {
    let cat: string
    let offset: number | undefined
    let limit: number | undefined

    if (typeof catOrParams === 'string') {
      cat = catOrParams
    } else {
      cat = catOrParams.cat
      offset = catOrParams.offset
      limit = catOrParams.limit
    }

    dispatch(changeCategoryAction(cat))
    getSongCategoryList(cat, offset ?? 0, limit ?? 35).then((res) => {
      console.log(res)
      dispatch(changeCategoryAction(res))
    })
  }
)


export type songsState = {
  FirstCategory: songsStateType
  currentCategory: string
  currentCategoryList: currentCategoryType
  PER_PAGE_NUMBER: number
}

const initialState: songsState = {
  FirstCategory: { all: { name: '', resourceCount: 0, imgId: 0, imgUrl: null, type: 0, category: 0, resourceType: 0, hot: false, activity: false }, sub: [], categories: { '0': '', '1': '', '2': '', '3': '', '4': '' } },
  currentCategory: '全部',
  currentCategoryList: { playlists: [], total: 0, more: false, cat: '全部' },
  PER_PAGE_NUMBER: 35
}

const songsSlice = createSlice({
  name: 'songs',
  initialState,
  reducers: {
    CategoryAction(state, action) {
      state.FirstCategory = action.payload
    },
    changeCategoryAction(state, action) {
      if (typeof action.payload === 'string') {
        state.currentCategory = action.payload
      } else {
        state.currentCategoryList = action.payload
      }
    }
  }
})

export default songsSlice.reducer
export const { CategoryAction, changeCategoryAction } = songsSlice.actions
